package com.minsf.springbootinit.judge.strategy;

import java.util.List;

import com.minsf.springbootinit.model.entity.Question;

import cn.hutool.json.JSONUtil;
import com.minsf.springbootinit.model.dto.question.JudgeCase;
import com.minsf.springbootinit.model.dto.question.JudgeConfig;
import com.minsf.springbootinit.judge.codesandbox.model.JudgeInfo;
import com.minsf.springbootinit.model.enums.QuestionSubmitStatusEnum;

/**
 * @Description
 * @Author minify
 * @Date 2024/3/9 19:13
 * @Project oj-backend
 */
public class DefaultJudgeStrategyImpl implements JudgeStrategy {
    @Override
    public JudgeInfo doJudge(JudgeContext judgeContext) {
        JudgeInfo judgeInfo = judgeContext.getJudgeInfo();
        List<String> inputList = judgeContext.getInputList();
        List<String> outputList = judgeContext.getOutputList();
        Question question = judgeContext.getQuestion();
        List<JudgeCase> judgeCaseList = judgeContext.getJudgeCaseList();
        QuestionSubmitStatusEnum judgmentOfQuestion = QuestionSubmitStatusEnum.JUDGMENT_SUCCESS;
        // 判断题目限制
        Integer memory = judgeInfo.getMemory();
        Integer time = judgeInfo.getTime();
        JudgeInfo judgeInfoResponse = new JudgeInfo();

        judgeInfoResponse.setTime(time);
        judgeInfoResponse.setMemory(memory);

        if (outputList.size() != inputList.size()) {
            judgmentOfQuestion = QuestionSubmitStatusEnum.JUDGMENT_FAILED;
            judgeInfoResponse.setMessage(judgmentOfQuestion.getName());
            return judgeInfoResponse;
        }
        for (int i = 0; i < judgeCaseList.size(); i++) {
            JudgeCase judgeCase1 = judgeCaseList.get(i);
            if (!judgeCase1.getOutput().equals(outputList.get(i))) {
                judgmentOfQuestion = QuestionSubmitStatusEnum.JUDGMENT_FAILED;
                judgeInfoResponse.setMessage(judgmentOfQuestion.getName());
                return judgeInfoResponse;
            }
        }

        String judgeConfigStr = question.getJudgeConfig();
        JudgeConfig judgeConfig = JSONUtil.toBean(judgeConfigStr, JudgeConfig.class);
        Long memoryLimit = judgeConfig.getMemoryLimit();
        Long timeLimit = judgeConfig.getTimeLimit();

        if (memory > memoryLimit) {
            judgmentOfQuestion = QuestionSubmitStatusEnum.JUDGMENT_FAILED;
            judgeInfoResponse.setMessage(judgmentOfQuestion.getName());
            return judgeInfoResponse;
        }
        if (time > timeLimit) {
            judgmentOfQuestion = QuestionSubmitStatusEnum.JUDGMENT_FAILED;
            judgeInfoResponse.setMessage(judgmentOfQuestion.getName());
            return judgeInfoResponse;
        }


        return judgeInfoResponse;
    }
}
